package com.sinoglobal.ningxia.activity.news;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.MyCollectionActivity;
import com.sinoglobal.ningxia.activity.mico.GSYVDHActivity;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.beans.CommentIdVo;
import com.sinoglobal.ningxia.beans.CommentSubmitVo;
import com.sinoglobal.ningxia.beans.NewsBean;
import com.sinoglobal.ningxia.beans.NewsDetailVo;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.beans.programInfoVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.DialogUtils;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.ToastBuilder;
import com.sinoglobal.ningxia.widget.KeyboardLayout;
import com.sinoglobal.ningxia.widget.KeyboardLayout.onKybdsChangeListener;

import java.text.MessageFormat;

public class NewsDetailActivity extends ShareAbstractActivity implements OnClickListener {
    WebView mWebView;
    Button btCommentLook;
    EditText etComment;
    ImageView ivCommentSend;
    NewsBean newsBean;
    NewsDetailVo newsDetailVo;
    ProgressDialog progressDialog;
    boolean isCollected;
    String videoUrl;
    private String isFromCollection = "";// 用于判断是否从我的收藏界面跳转过来
    private KeyboardLayout mainLayout;
    private final String FROM_COLLECTION = "1";//从收藏过来
    private final String COLLECTED = "1";//已收藏
    String html;//加载的网页内容
    //点击弹出评论Dialog
    private TextView tvComentBT;
    private LinearLayout llCollect;//点击收藏
    private LinearLayout llShare;//点击分享
    private LinearLayout llMessage;//点击查看评论
    private Dialog commentDialog;
    private ImageView ivCollect;//收藏的图标
    private AsyncTask<Void, Void, NewsDetailVo> asyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        openChenJInShi();
        newsBean = (NewsBean) getIntent().getSerializableExtra(NewsBean.class.getCanonicalName());
        ItktLog.i("newsbean==" + newsBean);
        String id = newsBean.getId();
        RemoteImpl.getInstance().getNewslookNum(this, id, 1).execute(new ResultCallback(this));
        initView();
        initDialog();
        loadData();
    }

    private void initDialog() {
        View commentDialogView = View.inflate(this, R.layout.dialog_comment_view, null);
        etComment = (EditText) commentDialogView.findViewById(R.id.comment_content);
        ivCommentSend = (ImageView) commentDialogView.findViewById(R.id.comment_submit);
        View view_space = (View) commentDialogView.findViewById(R.id.view_space);
        view_space.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (commentDialog != null) {
                    commentDialog.hide();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                }
            }
        });
        commentDialog = new Dialog(this, R.style.DialogStyleBottom);
        DialogUtils.getInstance(this).setDialog(commentDialogView, commentDialog, -1);
        ivCommentSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                commentDialog.hide();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 如果显示则隐藏，否则显示
                imm.hideSoftInputFromWindow(etComment.getWindowToken(), 0); // 强制隐藏键盘
                if (TextUtil.stringIsNull(etComment.getText().toString())) {
                    showShortToastMessage(getString(R.string.no_content_comment));
                    return;
                }
                if (etComment.getText().length() > 50) {
                    String info = getString(R.string.commentInfo);
                    info = MessageFormat.format(info, etComment.length());
                    showShortToastMessage(info);
                    return;
                }
                if (TextUtil.stringIsNull(FlyApplication.userId)) {
                    FlyUtil.intentForward(NewsDetailActivity.this, Login.class);
                    return;
                }
                ivCommentSend.setClickable(false);

                sendComment(etComment.getText().toString());
            }
        });
    }

    @Override
    protected void onRestart() {// 从登录界面返回 收藏状态从新请求。
        //Auto-generated method stub
        super.onRestart();
        loadData();
        if (html != null) {
            mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
        }
    }

    @SuppressLint("JavascriptInterface")
    private void initView() {
        isFromCollection = getIntent().getStringExtra(FlyApplication.isFromCollection);
        titleView.setText(getString(R.string.detail_news));


        btCommentLook = (Button) findViewById(R.id.bt1);
        btCommentLook.setVisibility(View.GONE);
        //---------------------------------------------------2017年2月9日16:03:59
        tvComentBT = (TextView) findViewById(R.id.tv_news_comment_bt);
        llCollect = (LinearLayout) findViewById(R.id.ll_new_comment_collect);
        llShare = (LinearLayout) findViewById(R.id.ll_new_comment_share);
        llMessage = (LinearLayout) findViewById(R.id.ll_new_comment_message);
        ivCollect = (ImageView) findViewById(R.id.iv_new_comment_collect);
        tvComentBT.setOnClickListener(this);
        llCollect.setOnClickListener(this);
        llShare.setOnClickListener(this);
        llMessage.setOnClickListener(this);
        //---------------------------------------------------END--2017年2月9日16:07:16-------
        progressDialog = new ProgressDialog(this);
        progressDialog.setCanceledOnTouchOutside(false);//点击外围不消失
        mWebView = (WebView) findViewById(R.id.wv1);
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.requestFocus();// 获取触摸焦点
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);// 取消滚动条
        // mWebView.getSettings().setBuiltInZoomControls(true); // 构建缩放控制
        // mWebView.getSettings().setSupportZoom(true); // 设置支持缩放
        mWebView.getSettings().setBlockNetworkImage(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setJavaScriptEnabled(true);// 设置支持javascript
        mWebView.addJavascriptInterface(this, "htmlistner");

        templateButtonLeft.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (FROM_COLLECTION.equals(isFromCollection)) {
                    Intent intent = new Intent(NewsDetailActivity.this, MyCollectionActivity.class);
                    NewsDetailActivity.this.startActivity(intent);
                    NewsDetailActivity.this.finish();
                } else {
                    NewsDetailActivity.this.finish();
                }
            }
        });
        mainLayout = (KeyboardLayout) findViewById(R.id.rely2);
        mainLayout.setOnkbdStateListener(new onKybdsChangeListener() {

            @Override
            public void onKeyBoardStateChange(int state) {
                if (state == KeyboardLayout.KEYBOARD_STATE_INIT) {
                } else if (state == KeyboardLayout.KEYBOARD_STATE_SHOW) {
                } else if (state == KeyboardLayout.KEYBOARD_STATE_HIDE) {
                }
            }
        });
    }


    // 注入js函数监听
    @SuppressLint("JavascriptInterface")
    private void addHtmlClickListner(String videoUrl) {
        Logger.e("1111111111111111111111111111111111111111111videoUrl:" + videoUrl);
        mWebView.loadUrl("javascript:(function(){" + "var obj =document.getElementById(\"comments\");"

                + "   obj.href=null;" + "    obj.onclick=function()  " + "    {  " + "        window.htmlistner.intentToCommentActivity(); " + "    }  " + "})()");
        if (TextUtil.stringIsNotNull(videoUrl)) {
            // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
            mWebView.loadUrl("javascript:(function(){" + "var obj = document.getElementById(\"img\"); " + "   obj.href=null;" + "    obj.onclick=function()  " + "    {  "
                    + "        window.htmlistner.openImage(this.src);  " + "    }  " + "})()");

        } else {
            mWebView.loadUrl("javascript:(function(){" + "var obj = document.getElementById(\"img\"); " + "  obj.href=null;" + "})()");
        }

    }

    @JavascriptInterface
    public void openImage(String img) {
        ItktLog.i("网页中的图片==" + img);
        ItktLog.i("网页中的视频地址==" + videoUrl);
        if (TextUtil.stringIsNotNull(videoUrl)) {// 跳转视频
//使用老版播放器
//            Intent intent = new Intent(this, VideoHActivity.class);
//            intent.putExtra(MContants.DATA_STRING, img);
//            intent.putExtra(programInfoVo.class.getName(), new programInfoVo(videoUrl));
//            FlyUtil.intentForward(this, intent);

//            //使用JCVD播放器
//            Intent intent = new Intent(this, JCVDHActivity.class);
//            intent.putExtra(MContants.DATA_STRING, img);
//            intent.putExtra(programInfoVo.class.getName(), new programInfoVo(videoUrl));
//            FlyUtil.intentForward(this, intent);
            //使用GSYVD播放器
            Intent intent = new Intent(this, GSYVDHActivity.class);
            intent.putExtra(MContants.DATA_STRING, img);
            intent.putExtra(programInfoVo.class.getName(), new programInfoVo(videoUrl));
            FlyUtil.intentForward(this, intent);

        }
    }

    private void addListener() {
        btCommentLook.setOnClickListener(this);
//        ivCommentSend.setOnClickListener(this);
    }


    private void setCollectState() {
        ivCollect.setSelected(isCollected);
    }

    private void loadData() {
        try {
            setView(RemoteImpl.getInstance().getNewsDetailVo(true, newsBean.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!EquipmentUtil.checkNetState(this)) {
            showShortToastMessage(getString(R.string.no_network));
            return;
        }
        asyncTask = new ItktAsyncTaskWithDialog<Void, Void, NewsDetailVo>(getString(R.string.loading_news), true, true) {

            @Override
            public NewsDetailVo before(Void... params) throws Exception {
                return RemoteImpl.getInstance().getNewsDetailVo(false, newsBean.getId());
            }

            @Override
            public void after(NewsDetailVo result) {
                if (asyncTask.isCancelled()) {//如果已被暂停则返回
                    return;
                }
                setView(result);

            }

            @Override
            public void exception() {

            }

        }.execute();


    }

    @Override
    public void onBackPressed() {
        if (FROM_COLLECTION.equals(isFromCollection)) {
            Intent intent = new Intent(NewsDetailActivity.this, MyCollectionActivity.class);
            NewsDetailActivity.this.startActivity(intent);
            NewsDetailActivity.this.finish();
        } else {
            NewsDetailActivity.this.finish();
        }
        super.onBackPressed();
    }

    @SuppressLint("JavascriptInterface")
    private void setView(NewsDetailVo result) {
        if (result != null) {
            newsDetailVo = result;
            if (Code.CODE_SUCCESS != result.getCode()) {
                return;
            }
            videoUrl = result.getVideo_url();
            mWebView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    //Auto-generated method stub
                    super.onPageStarted(view, url, favicon);
                    view.getSettings().setJavaScriptEnabled(true);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    mWebView.getSettings().setBlockNetworkImage(false);
                    // html加载完成之后，添加监听图片的点击js函数
                    addHtmlClickListner(videoUrl);
                }
            });
            html = result.getHtml();
            mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
            if (COLLECTED.equals(result.getCollect())) {// 已收藏
                isCollected = true;
                setCollectState();
            }
            addListener();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
            mWebView.stopLoading();
            mWebView.setWebChromeClient(null);
            mWebView.setWebViewClient(null);
            mWebView.destroy();
            mWebView = null;
        }
        if (asyncTask != null) {
            asyncTask.cancel(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.share:// 分享
                if (newsDetailVo != null && TextUtil.stringIsNotNull(newsDetailVo.getShareurl())) {

                    Logger.i("分享content:" + newsDetailVo.getShare_content() + "分享URL:" + newsDetailVo.getShareurl());
                    showPopwindow(true, newsDetailVo.getShare_content() + " " + newsDetailVo.getShareurl(), null, newsDetailVo.getShareurl());
                }
                break;
            case R.id.collect:// 收藏
                if (TextUtil.stringIsNotNull(FlyApplication.userId)) {// 已登录
                    if (isCollected) {// 已收藏
                        collect(MContants.ACTION_DEL);
                    } else {
                        collect(MContants.ACTION_ADD);
                    }
                } else {
                    FlyUtil.intentForward(this, Login.class);
                }
                break;
            case R.id.bt1:// 查看全部评论
                intentToCommentActivity();
                break;
            case R.id.tv_news_comment_bt:
                initDialog();
                commentDialog.show();
                etComment.requestFocus();
                openKeyboard();

                break;
            case R.id.ll_new_comment_collect:
                if (TextUtil.stringIsNotNull(FlyApplication.userId)) {// 已登录
                    if (isCollected) {// 已收藏
                        collect(MContants.ACTION_DEL);
                    } else {
                        collect(MContants.ACTION_ADD);
                    }
                } else {
                    FlyUtil.intentForward(this, Login.class);
                }
                break;
            case R.id.ll_new_comment_message:
                intentToCommentActivity();
                break;
            case R.id.ll_new_comment_share:
                if (newsDetailVo != null && TextUtil.stringIsNotNull(newsDetailVo.getShareurl())) {

                    showPopwindow(true, newsDetailVo.getShare_content() + " " + newsDetailVo.getShareurl(), null, newsDetailVo.getShareurl());
                }
                break;
        }
    }

    private void openKeyboard() {

        commentDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);//显示软键盘
        InputMethodManager imm = (InputMethodManager) NewsDetailActivity.
                this.getSystemService(NewsDetailActivity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); //显示软键盘


    }

    @JavascriptInterface
    public void intentToCommentActivity() {
        Logger.i("---------------------------------------------------------------------------");
        Intent intent = new Intent(this, NewsCommentActivity.class);
        intent.putExtra(NewsBean.class.getCanonicalName(), newsBean);
        FlyUtil.intentForward(this, intent);
    }

    private void collect(final byte collectState) {
        new ItktAsyncTaskWithDialog<Void, Void, RootVo>(null, false, true) {

            @Override
            public RootVo before(Void... params) throws Exception {
                return RemoteImpl.getInstance().add2DelCollect(FlyApplication.userId, MContants.TYPE_NEWS, collectState, newsBean.getId());
            }

            @Override
            public void after(RootVo result) {
                if (Code.CODE_SUCCESS == result.getCode()) {
                    isCollected = collectState == MContants.ACTION_ADD;
                    if (isCollected) {
                        ToastBuilder.getIntance(FlyApplication.context).showToast(getString(R.string.collectSuccess));
                    } else {
                        ToastBuilder.getIntance(FlyApplication.context).showToast(getString(R.string.collectCancel));

                    }
                    setCollectState();
                    if (SharedPreferenceUtil.getBoolean(FlyApplication.context, "isCollectSyn")) {

                    }
                }
            }

            @Override
            public void exception() {
            }
        }.execute();
    }

    private void sendComment(final String comment) {
        new AsyncTask<Void, Void, CommentIdVo>() {
            protected void onPreExecute() {
                // progressDialog.show();
            }

            @Override
            protected CommentIdVo doInBackground(Void... params) {
                try {
                    return RemoteImpl.getInstance().submitComment(new CommentSubmitVo(0, comment, newsBean.getId(), "1"), NewsDetailActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
//                    ivCommentSend.setClickable(true);
                }
                return null;
            }

            protected void onPostExecute(CommentIdVo result) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (result != null) {
                    ToastBuilder.getIntance(FlyApplication.context).showToast(result.getMessage());
                    if (Code.CODE_SUCCESS == result.getCode()) {
//                        etComment.setText(null);
                    }
                }
//                ivCommentSend.setClickable(true);
            }

            ;
        }.execute();

    }

}